package com.geyue.core.controller;

import com.geyue.common.toolbox.result.Res;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * 文件异步上传Controller
 *
 * @author JeffXu
 * @since 2016-03-14
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    @Value("${file.upload.path}")
    private String ROOT_PATH;

    @RequestMapping("/")
    public void upload(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        MultipartFile multipartFile = null;
        for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
            multipartFile = set.getValue();// 文件名
        }

        Res res = this.storeIOc(multipartFile);

        response.setCharacterEncoding("utf-8");
        response.addHeader("expires", "0");
        response.addHeader("Cache-Control", "no-cache");
        response.setContentType("text/html;charset=utf-8");
        try {
            response.getWriter().write(Json.toJson(res));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("返回json异常!");
        }
    }


    // 接受图片，返回文件地址
    private Res storeIOc(MultipartFile file) {

        if (file.isEmpty())
            return Res.fail("文件为空!");

        String _fileName = file.getOriginalFilename();
        String suffix = _fileName.substring(_fileName.lastIndexOf("."));
        // /**使用UUID生成文件名称**/
        String logImageName = UUID.randomUUID().toString() + suffix;

        File folder = new File(ROOT_PATH);

        if(!folder.exists())
            folder.mkdirs();

        String fileName = ROOT_PATH + logImageName;
        File restore = new File(fileName);
        try {
            file.transferTo(restore);
            String path = "/file/" + logImageName;
            return Res.success("上传成功!",path);
        } catch (Exception e) {
            return  Res.fail("服务器异常,稍后重试!");
        }
    }

}